<?php
/**
 * @title 350. 两个数组的交集 II - 哈希
 * @author start2004
 */

class Solution {

    /**
     * @param Integer[] $nums1
     * @param Integer[] $nums2
     * @return Integer[]
     */
    function intersect($nums1, $nums2) {
        /**
         * @since 2020-07-13 哈希数组
         */
        $hashArray = [];

        /**
         * @since 2020-07-13 nums1放到哈希
         */
        foreach ($nums1 as $num1){
            if(isset($hashArray[$num1])){
                $hashArray[$num1] += 1;
            } else {
                $hashArray[$num1] = 1;
            }
        }

        /**
         * @since 2020-07-13 公共数组
         */
        $result = [];
        foreach ($nums2 as $num2){
            if(isset($hashArray[$num2])){
                $result[] = $num2;

                /**
                 * @since 2020-07-13 减次数
                 */
                if($hashArray[$num2] == 1){
                    unset($hashArray[$num2]);
                } else {
                    $hashArray[$num2] -= 1;
                }
            } else {}
        }

        /**
         * @return
         */
        return $result;
    }
}

/**
 * @url http://127.0.0.1/leetcode/202007/20200713.php
 */
$datas = [
    [
        [1,2,2,1],
        [2,2],
    ],
    [
        [4,9,5,9],
        [9,4,9,8,4],
    ],
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    $obj = new Solution();
    $result = $obj->intersect($data[0], $data[1]);

    var_dump($data);
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
